<template>
  <div class="logs-container">
    <div class="page-header">
      <h1>系统日志管理</h1>
      <div class="header-actions">
        <button class="btn btn-primary" @click="exportLogs">
          <i class="fa fa-download"></i> 导出日志
        </button>
        <button class="btn btn-success" @click="refreshLogs">
          <i class="fa fa-refresh"></i> 刷新日志
        </button>
      </div>
    </div>
    
    <!-- 搜索和筛选区域 -->
    <div class="filter-section">
      <div class="filter-row">
        <div class="filter-item">
          <label>操作类型</label>
          <select v-model="filters.actionType" @change="onFilterChange">
            <option value="">全部</option>
            <option value="login">登录</option>
            <option value="logout">登出</option>
            <option value="create">创建</option>
            <option value="update">更新</option>
            <option value="delete">删除</option>
            <option value="upload">上传</option>
            <option value="download">下载</option>
            <option value="publish">发布</option>
            <option value="review">审核</option>
            <option value="settings">设置修改</option>
          </select>
        </div>
        
        <div class="filter-item">
          <label>操作对象</label>
          <select v-model="filters.targetType" @change="onFilterChange">
            <option value="">全部</option>
            <option value="user">用户</option>
            <option value="video">视频</option>
            <option value="category">分类</option>
            <option value="tag">标签</option>
            <option value="comment">评论</option>
            <option value="feedback">反馈</option>
            <option value="system">系统</option>
          </select>
        </div>
        
        <div class="filter-item">
          <label>操作用户</label>
          <input 
            v-model="filters.username" 
            type="text" 
            placeholder="输入用户名"
            @input="onFilterChange"
          />
        </div>
        
        <div class="filter-item">
          <label>状态</label>
          <select v-model="filters.status" @change="onFilterChange">
            <option value="">全部</option>
            <option value="success">成功</option>
            <option value="fail">失败</option>
            <option value="warning">警告</option>
            <option value="info">信息</option>
          </select>
        </div>
      </div>
      
      <div class="filter-row">
        <div class="filter-item date-range">
          <label>时间范围</label>
          <div class="date-range-inputs">
            <input v-model="filters.startDate" type="date" @change="onFilterChange" />
            <span>至</span>
            <input v-model="filters.endDate" type="date" @change="onFilterChange" />
          </div>
        </div>
        
        <div class="filter-item full-width">
          <label>关键词搜索</label>
          <div class="search-input-wrapper">
            <input 
              v-model="filters.keyword" 
              type="text" 
              placeholder="输入IP地址、操作描述或操作对象ID等关键词"
              class="search-input"
              @input="onFilterChange"
            />
            <button class="search-btn" @click="onSearch">
              <i class="fa fa-search"></i>
            </button>
          </div>
        </div>
      </div>
      
      <div class="filter-info">
        <span class="filter-count">共筛选出 <strong>{{ filteredLogs.length }}</strong> 条日志记录</span>
        <button class="reset-filter-btn" @click="resetFilters">
          <i class="fa fa-undo"></i> 重置筛选条件
        </button>
      </div>
    </div>
    
    <!-- 日志列表 -->
    <div class="logs-table-container">
      <table class="logs-table">
        <thead>
          <tr>
            <th>
              <input v-model="selectAll" type="checkbox" @change="toggleSelectAll" />
            </th>
            <th>ID</th>
            <th>操作时间</th>
            <th>操作用户</th>
            <th>操作类型</th>
            <th>操作对象</th>
            <th>IP地址</th>
            <th>状态</th>
            <th>描述</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-if="loading" class="loading-row">
            <td colspan="10" class="loading-cell">
              <div class="loading-spinner">
                <i class="fa fa-circle-o-notch fa-spin"></i>
                <span>加载中...</span>
              </div>
            </td>
          </tr>
          <tr v-else-if="paginatedLogs.length === 0" class="empty-row">
            <td colspan="10" class="empty-cell">
              <div class="empty-state">
                <i class="fa fa-file-text-o"></i>
                <p>暂无日志记录</p>
              </div>
            </td>
          </tr>
          <tr 
            v-for="log in paginatedLogs" 
            v-else 
            :key="log.id"
            class="log-row"
            :class="{
              'status-success': log.status === 'success',
              'status-fail': log.status === 'fail',
              'status-warning': log.status === 'warning',
              'status-info': log.status === 'info',
              'selected': selectedLogs.includes(log.id)
            }"
          >
            <td>
              <input v-model="selectedLogs" type="checkbox" :value="log.id" />
            </td>
            <td class="log-id">{{ log.id }}</td>
            <td class="log-time">{{ formatDateTime(log.timestamp) }}</td>
            <td class="log-user">
              <div class="user-info">
                <div class="user-avatar" :style="{ backgroundColor: getUserAvatarColor(log.username) }">
                  {{ getInitial(log.username) }}
                </div>
                <div class="user-details">
                  <div class="username">{{ log.username }}</div>
                  <div class="user-role">{{ getUserRoleText(log.userRole) }}</div>
                </div>
              </div>
            </td>
            <td class="log-action">
              <span class="action-badge" :class="getActionTypeClass(log.actionType)">
                {{ getActionTypeText(log.actionType) }}
              </span>
            </td>
            <td class="log-target">
              <div class="target-info">
                <div class="target-type">{{ getTargetTypeText(log.targetType) }}</div>
                <div class="target-id">#{{ log.targetId }}</div>
              </div>
            </td>
            <td class="log-ip">{{ log.ipAddress }}</td>
            <td class="log-status">
              <span class="status-badge" :class="getStatusClass(log.status)">
                <i class="fa" :class="getStatusIcon(log.status)"></i>
                {{ getStatusText(log.status) }}
              </span>
            </td>
            <td class="log-description" :title="log.description">
              {{ truncateText(log.description, 50) }}
            </td>
            <td class="log-actions">
              <button class="view-btn" title="查看详情" @click="viewLogDetails(log)">
                <i class="fa fa-eye"></i>
              </button>
              <button 
                v-if="log.status === 'fail'" 
                class="debug-btn" 
                title="查看错误详情" 
                @click="viewDebugInfo(log)"
              >
                <i class="fa fa-bug"></i>
              </button>
            </td>
          </tr>
        </tbody>
      </table>
    </div>
    
    <!-- 分页控件 -->
    <div class="pagination-container">
      <div class="pagination-info">
        显示 {{ (currentPage - 1) * pageSize + 1 }} 至 {{ Math.min(currentPage * pageSize, filteredLogs.length) }} 条，
        共 {{ filteredLogs.length }} 条记录
      </div>
      <div class="pagination-controls">
        <button 
          class="page-btn" 
          :disabled="currentPage === 1" 
          @click="currentPage = 1"
        >
          <i class="fa fa-angle-double-left"></i>
        </button>
        <button 
          class="page-btn" 
          :disabled="currentPage === 1" 
          @click="currentPage--"
        >
          <i class="fa fa-angle-left"></i>
        </button>
        
        <button 
          v-for="page in visiblePages" 
          :key="page"
          class="page-btn" 
          :class="{ active: page === currentPage }"
          @click="currentPage = page"
        >
          {{ page }}
        </button>
        
        <button 
          class="page-btn" 
          :disabled="currentPage === totalPages" 
          @click="currentPage++"
        >
          <i class="fa fa-angle-right"></i>
        </button>
        <button 
          class="page-btn" 
          :disabled="currentPage === totalPages" 
          @click="currentPage = totalPages"
        >
          <i class="fa fa-angle-double-right"></i>
        </button>
      </div>
      <div class="page-size-selector">
        <label>每页显示：</label>
        <select v-model="pageSize" @change="onPageSizeChange">
          <option value="10">10</option>
          <option value="20">20</option>
          <option value="50">50</option>
          <option value="100">100</option>
        </select>
      </div>
    </div>
    
    <!-- 批量操作 -->
    <div v-if="selectedLogs.length > 0" class="batch-actions">
      <div class="selected-count">已选择 {{ selectedLogs.length }} 条记录</div>
      <div class="batch-buttons">
        <button class="btn btn-danger" @click="confirmBatchDelete">
          <i class="fa fa-trash"></i> 批量删除
        </button>
        <button class="btn btn-primary" @click="exportSelectedLogs">
          <i class="fa fa-download"></i> 导出选中
        </button>
        <button class="btn btn-secondary" @click="clearSelection">
          <i class="fa fa-times"></i> 取消选择
        </button>
      </div>
    </div>
    
    <!-- 日志详情对话框 -->
    <div v-if="showLogDetails" class="modal-overlay" @click.self="closeLogDetails">
      <div class="modal-container">
        <div class="modal-header">
          <h3>日志详情</h3>
          <button class="close-btn" @click="closeLogDetails">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="modal-content">
          <div class="detail-grid">
            <div class="detail-item">
              <label>日志ID:</label>
              <span>{{ currentLogDetail.id }}</span>
            </div>
            <div class="detail-item">
              <label>操作时间:</label>
              <span>{{ formatDateTime(currentLogDetail.timestamp) }}</span>
            </div>
            <div class="detail-item">
              <label>操作用户:</label>
              <span>{{ currentLogDetail.username }}</span>
            </div>
            <div class="detail-item">
              <label>用户角色:</label>
              <span>{{ getUserRoleText(currentLogDetail.userRole) }}</span>
            </div>
            <div class="detail-item">
              <label>用户ID:</label>
              <span>{{ currentLogDetail.userId }}</span>
            </div>
            <div class="detail-item">
              <label>IP地址:</label>
              <span>{{ currentLogDetail.ipAddress }}</span>
            </div>
            <div class="detail-item">
              <label>浏览器:</label>
              <span>{{ currentLogDetail.userAgent }}</span>
            </div>
            <div class="detail-item">
              <label>操作类型:</label>
              <span class="action-badge" :class="getActionTypeClass(currentLogDetail.actionType)">
                {{ getActionTypeText(currentLogDetail.actionType) }}
              </span>
            </div>
            <div class="detail-item">
              <label>操作对象类型:</label>
              <span>{{ getTargetTypeText(currentLogDetail.targetType) }}</span>
            </div>
            <div class="detail-item">
              <label>操作对象ID:</label>
              <span>#{{ currentLogDetail.targetId }}</span>
            </div>
            <div class="detail-item">
              <label>操作状态:</label>
              <span class="status-badge" :class="getStatusClass(currentLogDetail.status)">
                <i class="fa" :class="getStatusIcon(currentLogDetail.status)"></i>
                {{ getStatusText(currentLogDetail.status) }}
              </span>
            </div>
            <div class="detail-item">
              <label>响应时间:</label>
              <span>{{ currentLogDetail.responseTime }}ms</span>
            </div>
            <div class="detail-item full-width">
              <label>操作描述:</label>
              <div class="description-content">{{ currentLogDetail.description }}</div>
            </div>
            <div v-if="currentLogDetail.oldData" class="detail-item full-width">
              <label>变更前数据:</label>
              <pre class="code-block">{{ formatJson(currentLogDetail.oldData) }}</pre>
            </div>
            <div v-if="currentLogDetail.newData" class="detail-item full-width">
              <label>变更后数据:</label>
              <pre class="code-block">{{ formatJson(currentLogDetail.newData) }}</pre>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeLogDetails">关闭</button>
        </div>
      </div>
    </div>
    
    <!-- 错误详情对话框 -->
    <div v-if="showDebugInfo" class="modal-overlay" @click.self="closeDebugInfo">
      <div class="modal-container">
        <div class="modal-header">
          <h3>错误详情</h3>
          <button class="close-btn" @click="closeDebugInfo">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="modal-content">
          <div class="error-info">
            <div class="error-title">
              <i class="fa fa-exclamation-triangle"></i>
              {{ currentErrorLog.errorMessage }}
            </div>
            <div class="error-details">
              <h4>错误堆栈:</h4>
              <pre class="code-block error-stack">{{ currentErrorLog.stackTrace }}</pre>
            </div>
            <div v-if="currentErrorLog.errorData" class="error-data">
              <h4>错误数据:</h4>
              <pre class="code-block">{{ formatJson(currentErrorLog.errorData) }}</pre>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="btn btn-primary" @click="copyErrorDetails">复制详情</button>
          <button class="btn btn-secondary" @click="closeDebugInfo">关闭</button>
        </div>
      </div>
    </div>
    
    <!-- 确认删除对话框 -->
    <div v-if="showDeleteConfirm" class="modal-overlay" @click.self="closeDeleteConfirm">
      <div class="modal-container small">
        <div class="modal-header">
          <h3>确认删除</h3>
          <button class="close-btn" @click="closeDeleteConfirm">
            <i class="fa fa-times"></i>
          </button>
        </div>
        <div class="modal-content">
          <p>确定要删除选中的 {{ selectedLogs.length }} 条日志记录吗？</p>
          <p class="warning-text">此操作不可恢复，请谨慎操作。</p>
        </div>
        <div class="modal-footer">
          <button class="btn btn-secondary" @click="closeDeleteConfirm">取消</button>
          <button class="btn btn-danger" @click="batchDeleteLogs">确定删除</button>
        </div>
      </div>
    </div>
    
    <!-- 导出成功提示 -->
    <div v-if="showExportSuccess" class="toast success">
      <i class="fa fa-check-circle"></i>
      <span>日志导出成功！</span>
      <button class="close-btn" @click="showExportSuccess = false">
        <i class="fa fa-times"></i>
      </button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'LogsView',
  data() {
    return {
      // 日志数据（模拟数据）
      logs: [],
      
      // 筛选条件
      filters: {
        actionType: '',
        targetType: '',
        username: '',
        status: '',
        startDate: '',
        endDate: '',
        keyword: '',
      },
      
      // 分页设置
      currentPage: 1,
      pageSize: 20,
      
      // 选中的日志
      selectedLogs: [],
      selectAll: false,
      
      // UI状态
      loading: false,
      showLogDetails: false,
      showDebugInfo: false,
      showDeleteConfirm: false,
      showExportSuccess: false,
      
      // 当前查看的日志详情
      currentLogDetail: {},
      currentErrorLog: {},
    }
  },
  computed: {
    // 筛选后的日志
    filteredLogs() {
      return this.logs.filter(log => {
        // 按操作类型筛选
        if (this.filters.actionType && log.actionType !== this.filters.actionType) {
          return false
        }
        
        // 按操作对象筛选
        if (this.filters.targetType && log.targetType !== this.filters.targetType) {
          return false
        }
        
        // 按用户名筛选
        if (this.filters.username && !log.username.toLowerCase().includes(this.filters.username.toLowerCase())) {
          return false
        }
        
        // 按状态筛选
        if (this.filters.status && log.status !== this.filters.status) {
          return false
        }
        
        // 按时间范围筛选
        if (this.filters.startDate) {
          const logDate = new Date(log.timestamp).toISOString().split('T')[0]
          if (logDate < this.filters.startDate) {
            return false
          }
        }
        
        if (this.filters.endDate) {
          const logDate = new Date(log.timestamp).toISOString().split('T')[0]
          if (logDate > this.filters.endDate) {
            return false
          }
        }
        
        // 按关键词搜索
        if (this.filters.keyword) {
          const keyword = this.filters.keyword.toLowerCase()
          return (
            log.ipAddress.toLowerCase().includes(keyword) ||
            log.description.toLowerCase().includes(keyword) ||
            log.targetId.toString().includes(keyword) ||
            log.username.toLowerCase().includes(keyword) ||
            log.id.toString().includes(keyword)
          )
        }
        
        return true
      })
    },
    
    // 分页后的日志
    paginatedLogs() {
      const startIndex = (this.currentPage - 1) * this.pageSize
      const endIndex = startIndex + this.pageSize
      return this.filteredLogs.slice(startIndex, endIndex)
    },
    
    // 总页数
    totalPages() {
      return Math.ceil(this.filteredLogs.length / this.pageSize)
    },
    
    // 可见的页码
    visiblePages() {
      const total = this.totalPages
      const current = this.currentPage
      const pages = []
      
      // 显示当前页附近的页码，最多显示9个
      let startPage = Math.max(1, current - 4)
      let endPage = Math.min(total, startPage + 8)
      
      // 如果总页数少于9，直接显示所有页码
      if (total <= 9) {
        startPage = 1
        endPage = total
      }
      // 如果右侧页码不足，调整起始页码
      else if (endPage === total) {
        startPage = Math.max(1, total - 8)
      }
      
      for (let i = startPage; i <= endPage; i++) {
        pages.push(i)
      }
      
      return pages
    },
  },
  mounted() {
    // 初始化模拟日志数据
    this.initializeMockData()
    
    // 设置默认日期范围为最近30天
    const today = new Date()
    const lastMonth = new Date()
    lastMonth.setMonth(lastMonth.getMonth() - 1)
    
    this.filters.endDate = today.toISOString().split('T')[0]
    this.filters.startDate = lastMonth.toISOString().split('T')[0]
    
    // 监听全选状态变化
    this.$watch('selectAll', (newVal) => {
      if (newVal) {
        // 选中当前页所有日志
        this.selectedLogs = this.paginatedLogs.map(log => log.id)
      } else {
        // 取消所有选中
        this.selectedLogs = []
      }
    })
  },
  methods: {
    // 初始化模拟数据
    initializeMockData() {
      const now = new Date()
      const logs = []
      const actionTypes = ['login', 'logout', 'create', 'update', 'delete', 'upload', 'download', 'publish', 'review', 'settings']
      const targetTypes = ['user', 'video', 'category', 'tag', 'comment', 'feedback', 'system']
      const statuses = ['success', 'fail', 'warning', 'info']
      const usernames = ['admin', 'editor1', 'editor2', 'creator1', 'creator2', 'user1', 'user2', 'user3']
      const userRoles = ['admin', 'editor', 'creator', 'user']
      
      // 生成20条模拟日志
      for (let i = 1; i <= 20; i++) {
        const timestamp = new Date(now.getTime() - Math.floor(Math.random() * 30 * 24 * 60 * 60 * 1000)) // 最近30天内
        const actionType = actionTypes[Math.floor(Math.random() * actionTypes.length)]
        const targetType = targetTypes[Math.floor(Math.random() * targetTypes.length)]
        const status = statuses[Math.floor(Math.random() * statuses.length)]
        const username = usernames[Math.floor(Math.random() * usernames.length)]
        const userRole = userRoles[Math.floor(Math.random() * userRoles.length)]
        const targetId = Math.floor(Math.random() * 1000) + 1
        
        // 根据操作类型生成描述
        let description = ''
        switch(actionType) {
          case 'login':
            description = `${username} 用户登录系统`
            break
          case 'logout':
            description = `${username} 用户退出系统`
            break
          case 'create':
            description = `${username} 创建了新的${this.getTargetTypeText(targetType)}`
            break
          case 'update':
            description = `${username} 更新了${this.getTargetTypeText(targetType)} #${targetId}`
            break
          case 'delete':
            description = `${username} 删除了${this.getTargetTypeText(targetType)} #${targetId}`
            break
          case 'upload':
            description = `${username} 上传了新的视频内容`
            break
          case 'download':
            description = `${username} 下载了系统数据报表`
            break
          case 'publish':
            description = `${username} 发布了${this.getTargetTypeText(targetType)} #${targetId}`
            break
          case 'review':
            description = `${username} 审核了${this.getTargetTypeText(targetType)} #${targetId}`
            break
          case 'settings':
            description = `${username} 修改了系统设置`
            break
        }
        
        // 随机生成IP地址
        const ipAddress = `${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}.${Math.floor(Math.random() * 256)}`
        
        // 模拟浏览器信息
        const userAgent = `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${Math.floor(Math.random() * 100)}.0.${Math.floor(Math.random() * 1000)}.${Math.floor(Math.random() * 100)} Safari/537.36`
        
        // 响应时间
        const responseTime = Math.floor(Math.random() * 500) + 50
        
        // 错误日志详情
        const errorInfo = status === 'fail' ? {
          errorMessage: '操作失败：数据库连接错误',
          stackTrace: 'Error: Database connection failed\n    at connectDB (database.js:42)\n    at processRequest (server.js:156)\n    at Layer.handle [as handle_request] (express.js:395)\n    at next (router.js:284)',
          errorData: { code: 500, sql: 'SELECT * FROM users WHERE id = ?', params: [targetId] },
        } : null
        
        logs.push({
          id: i,
          timestamp: timestamp.toISOString(),
          username,
          userId: Math.floor(Math.random() * 100) + 1,
          userRole,
          actionType,
          targetType,
          targetId,
          description,
          ipAddress,
          userAgent,
          status,
          responseTime,
          oldData: actionType === 'update' ? { name: '旧名称', status: 'inactive' } : null,
          newData: actionType === 'update' ? { name: '新名称', status: 'active' } : null,
          ...errorInfo,
        })
      }
      
      // 按时间排序，最新的在前
      logs.sort((a, b) => new Date(b.timestamp) - new Date(a.timestamp))
      
      this.logs = logs
    },
    
    // 格式化日期时间
    formatDateTime(dateString) {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit',
      })
    },
    
    // 格式化JSON
    formatJson(jsonData) {
      return JSON.stringify(jsonData, null, 2)
    },
    
    // 获取操作类型文本
    getActionTypeText(actionType) {
      const actionMap = {
        'login': '登录',
        'logout': '登出',
        'create': '创建',
        'update': '更新',
        'delete': '删除',
        'upload': '上传',
        'download': '下载',
        'publish': '发布',
        'review': '审核',
        'settings': '设置修改',
      }
      return actionMap[actionType] || actionType
    },
    
    // 获取操作类型样式类
    getActionTypeClass(actionType) {
      const classMap = {
        'login': 'action-login',
        'logout': 'action-logout',
        'create': 'action-create',
        'update': 'action-update',
        'delete': 'action-delete',
        'upload': 'action-upload',
        'download': 'action-download',
        'publish': 'action-publish',
        'review': 'action-review',
        'settings': 'action-settings',
      }
      return classMap[actionType] || ''
    },
    
    // 获取操作对象类型文本
    getTargetTypeText(targetType) {
      const targetMap = {
        'user': '用户',
        'video': '视频',
        'category': '分类',
        'tag': '标签',
        'comment': '评论',
        'feedback': '反馈',
        'system': '系统',
      }
      return targetMap[targetType] || targetType
    },
    
    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        'success': '成功',
        'fail': '失败',
        'warning': '警告',
        'info': '信息',
      }
      return statusMap[status] || status
    },
    
    // 获取状态图标
    getStatusIcon(status) {
      const iconMap = {
        'success': 'fa-check',
        'fail': 'fa-times',
        'warning': 'fa-exclamation-triangle',
        'info': 'fa-info-circle',
      }
      return iconMap[status] || 'fa-circle'
    },
    
    // 获取状态样式类
    getStatusClass(status) {
      return `status-${status}`
    },
    
    // 获取用户角色文本
    getUserRoleText(role) {
      const roleMap = {
        'admin': '超级管理员',
        'editor': '编辑',
        'creator': '创作者',
        'user': '普通用户',
      }
      return roleMap[role] || role
    },
    
    // 获取用户头像颜色
    getUserAvatarColor(username) {
      const colors = ['#3498db', '#e74c3c', '#2ecc71', '#9b59b6', '#f39c12', '#1abc9c']
      let hash = 0
      for (let i = 0; i < username.length; i++) {
        hash = username.charCodeAt(i) + ((hash << 5) - hash)
      }
      return colors[Math.abs(hash) % colors.length]
    },
    
    // 获取用户名首字母
    getInitial(username) {
      return username.charAt(0).toUpperCase()
    },
    
    // 截断文本
    truncateText(text, maxLength) {
      if (!text) return ''
      return text.length > maxLength ? text.substring(0, maxLength) + '...' : text
    },
    
    // 筛选条件变化
    onFilterChange() {
      this.currentPage = 1 // 重置到第一页
      this.selectedLogs = [] // 清空选中状态
      this.selectAll = false // 取消全选
    },
    
    // 搜索
    onSearch() {
      this.currentPage = 1
    },
    
    // 重置筛选条件
    resetFilters() {
      this.filters = {
        actionType: '',
        targetType: '',
        username: '',
        status: '',
        startDate: '',
        endDate: '',
        keyword: '',
      }
      this.currentPage = 1
      this.selectedLogs = []
      this.selectAll = false
    },
    
    // 切换全选
    toggleSelectAll() {
      if (this.selectAll) {
        this.selectedLogs = this.paginatedLogs.map(log => log.id)
      } else {
        this.selectedLogs = []
      }
    },
    
    // 查看日志详情
    viewLogDetails(log) {
      this.currentLogDetail = { ...log }
      this.showLogDetails = true
    },
    
    // 关闭日志详情
    closeLogDetails() {
      this.showLogDetails = false
      this.currentLogDetail = {}
    },
    
    // 查看错误详情
    viewDebugInfo(log) {
      this.currentErrorLog = {
        errorMessage: log.errorMessage || '操作失败',
        stackTrace: log.stackTrace || '未提供错误堆栈信息',
        errorData: log.errorData || null,
      }
      this.showDebugInfo = true
    },
    
    // 关闭错误详情
    closeDebugInfo() {
      this.showDebugInfo = false
      this.currentErrorLog = {}
    },
    
    // 复制错误详情
    copyErrorDetails() {
      const errorDetails = `错误信息: ${this.currentErrorLog.errorMessage}\n\n错误堆栈:\n${this.currentErrorLog.stackTrace}\n\n错误数据:\n${this.currentErrorLog.errorData ? JSON.stringify(this.currentErrorLog.errorData, null, 2) : '无'}`
      
      // 创建临时文本区域用于复制
      const textArea = document.createElement('textarea')
      textArea.value = errorDetails
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      
      // 显示复制成功提示（这里简化处理，实际项目中可以使用更友好的提示组件）
      alert('错误详情已复制到剪贴板')
    },
    
    // 分页大小变化
    onPageSizeChange() {
      this.currentPage = 1 // 重置到第一页
      this.selectedLogs = [] // 清空选中状态
      this.selectAll = false // 取消全选
    },
    
    // 确认批量删除
    confirmBatchDelete() {
      if (this.selectedLogs.length === 0) return
      this.showDeleteConfirm = true
    },
    
    // 关闭删除确认对话框
    closeDeleteConfirm() {
      this.showDeleteConfirm = false
    },
    
    // 批量删除日志
    batchDeleteLogs() {
      // 在实际项目中，这里应该调用API删除日志
      this.logs = this.logs.filter(log => !this.selectedLogs.includes(log.id))
      
      this.showDeleteConfirm = false
      this.selectedLogs = []
      this.selectAll = false
      
      // 重置到第一页
      if (this.currentPage > this.totalPages && this.totalPages >= 1) {
        this.currentPage = this.totalPages
      }
    },
    
    // 清空选择
    clearSelection() {
      this.selectedLogs = []
      this.selectAll = false
    },
    
    // 导出日志
    exportLogs() {
      // 在实际项目中，这里应该调用API导出日志
      // 这里模拟导出操作
      setTimeout(() => {
        this.showExportSuccess = true
        setTimeout(() => {
          this.showExportSuccess = false
        }, 3000)
      }, 500)
    },
    
    // 导出选中的日志
    exportSelectedLogs() {
      // 在实际项目中，这里应该调用API导出选中的日志
      this.exportLogs()
    },
    
    // 刷新日志
    refreshLogs() {
      this.loading = true
      
      // 在实际项目中，这里应该调用API重新获取日志
      // 这里模拟刷新操作
      setTimeout(() => {
        this.initializeMockData()
        this.selectedLogs = []
        this.selectAll = false
        this.loading = false
      }, 800)
    },
  },
}
</script>

<style scoped>
.logs-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.page-header h1 {
  color: #2c3e50;
  margin: 0;
  font-size: 24px;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.btn {
  padding: 10px 15px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 5px;
  transition: all 0.3s;
}

.btn-primary {
  background: #3498db;
  color: white;
}

.btn-primary:hover {
  background: #2980b9;
}

.btn-success {
  background: #2ecc71;
  color: white;
}

.btn-success:hover {
  background: #27ae60;
}

.btn-danger {
  background: #e74c3c;
  color: white;
}

.btn-danger:hover {
  background: #c0392b;
}

.btn-secondary {
  background: #95a5a6;
  color: white;
}

.btn-secondary:hover {
  background: #7f8c8d;
}

/* 筛选区域 */
.filter-section {
  background: white;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  margin-bottom: 20px;
}

.filter-row {
  display: flex;
  gap: 20px;
  margin-bottom: 15px;
  flex-wrap: wrap;
}

.filter-item {
  flex: 1;
  min-width: 200px;
}

.filter-item.full-width {
  flex: 1 1 100%;
  min-width: 100%;
}

.filter-item label {
  display: block;
  margin-bottom: 8px;
  font-weight: 500;
  color: #2c3e50;
  font-size: 14px;
}

.filter-item select,
.filter-item input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.filter-item select:focus,
.filter-item input:focus {
  outline: none;
  border-color: #3498db;
}

.date-range-inputs {
  display: flex;
  align-items: center;
  gap: 10px;
}

.date-range-inputs input {
  flex: 1;
}

.search-input-wrapper {
  display: flex;
  position: relative;
}

.search-input {
  flex: 1;
  padding-right: 40px;
}

.search-btn {
  position: absolute;
  right: 0;
  top: 0;
  bottom: 0;
  width: 40px;
  border: none;
  background: #3498db;
  color: white;
  border-radius: 0 6px 6px 0;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: background 0.3s;
}

.search-btn:hover {
  background: #2980b9;
}

.filter-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-top: 15px;
  border-top: 1px solid #eee;
  font-size: 14px;
}

.filter-count {
  color: #7f8c8d;
}

.reset-filter-btn {
  background: #f8f9fa;
  border: 1px solid #ddd;
  border-radius: 6px;
  padding: 8px 15px;
  cursor: pointer;
  font-size: 14px;
  color: #7f8c8d;
  transition: all 0.3s;
}

.reset-filter-btn:hover {
  background: #e9ecef;
  color: #343a40;
}

/* 日志表格 */
.logs-table-container {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
  overflow-x: auto;
  margin-bottom: 20px;
}

.logs-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.logs-table th {
  background: #f8f9fa;
  padding: 12px;
  text-align: left;
  font-weight: 600;
  color: #2c3e50;
  border-bottom: 2px solid #e9ecef;
  white-space: nowrap;
}

.logs-table td {
  padding: 12px;
  border-bottom: 1px solid #eee;
}

.log-row:hover {
  background: #f8f9fa;
}

.log-row.selected {
  background: #e3f2fd;
}

.status-success {
  border-left: 3px solid #2ecc71;
}

.status-fail {
  border-left: 3px solid #e74c3c;
}

.status-warning {
  border-left: 3px solid #f39c12;
}

.status-info {
  border-left: 3px solid #3498db;
}

.log-id {
  font-weight: 600;
  color: #7f8c8d;
}

.log-time {
  white-space: nowrap;
  color: #34495e;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 10px;
}

.user-avatar {
  width: 32px;
  height: 32px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-weight: 600;
  font-size: 12px;
}

.user-details {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.username {
  font-weight: 500;
  color: #2c3e50;
}

.user-role {
  font-size: 12px;
  color: #7f8c8d;
}

.action-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  display: inline-block;
}

.action-login { background: #e3f2fd; color: #1976d2; }
.action-logout { background: #e8f5e9; color: #388e3c; }
.action-create { background: #e8f5e9; color: #388e3c; }
.action-update { background: #fff3e0; color: #f57c00; }
.action-delete { background: #ffebee; color: #d32f2f; }
.action-upload { background: #e1f5fe; color: #0288d1; }
.action-download { background: #f3e5f5; color: #7b1fa2; }
.action-publish { background: #e8f5e9; color: #388e3c; }
.action-review { background: #fff8e1; color: #fbc02d; }
.action-settings { background: #f5f5f5; color: #616161; }

.target-info {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

.target-type {
  font-weight: 500;
  color: #2c3e50;
}

.target-id {
  font-size: 12px;
  color: #7f8c8d;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

.status-success {
  background: #e8f5e9; 
  color: #388e3c;
}

.status-fail {
  background: #ffebee; 
  color: #d32f2f;
}

.status-warning {
  background: #fff8e1; 
  color: #fbc02d;
}

.status-info {
  background: #e3f2fd; 
  color: #1976d2;
}

.log-description {
  max-width: 300px;
  color: #34495e;
  word-break: break-word;
}

.log-actions {
  display: flex;
  gap: 5px;
}

.view-btn,
.debug-btn {
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: all 0.3s;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 30px;
  height: 30px;
}

.view-btn {
  background: #3498db;
  color: white;
}

.view-btn:hover {
  background: #2980b9;
}

.debug-btn {
  background: #e74c3c;
  color: white;
}

.debug-btn:hover {
  background: #c0392b;
}

/* 加载和空状态 */
.loading-row,
.empty-row {
  text-align: center;
}

.loading-cell,
.empty-cell {
  padding: 40px;
}

.loading-spinner,
.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 15px;
  color: #7f8c8d;
}

.loading-spinner i {
  font-size: 30px;
}

.empty-state i {
  font-size: 40px;
}

/* 分页控件 */
.pagination-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.pagination-info {
  color: #7f8c8d;
  font-size: 14px;
}

.pagination-controls {
  display: flex;
  align-items: center;
  gap: 5px;
}

.page-btn {
  width: 36px;
  height: 36px;
  border: 1px solid #ddd;
  background: white;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  transition: all 0.3s;
}

.page-btn:hover:not(:disabled) {
  background: #f8f9fa;
  border-color: #3498db;
}

.page-btn.active {
  background: #3498db;
  color: white;
  border-color: #3498db;
}

.page-btn:disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.page-size-selector {
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 14px;
}

.page-size-selector select {
  padding: 6px 10px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

/* 批量操作 */
.batch-actions {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 15px 20px;
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex-wrap: wrap;
  gap: 15px;
}

.selected-count {
  font-weight: 500;
  color: #2c3e50;
}

.batch-buttons {
  display: flex;
  gap: 10px;
}

/* 模态框 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-container {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 900px;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  box-shadow: 0 5px 25px rgba(0, 0, 0, 0.2);
}

.modal-container.small {
  max-width: 500px;
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #eee;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 18px;
}

.close-btn {
  background: none;
  border: none;
  font-size: 20px;
  cursor: pointer;
  color: #7f8c8d;
  padding: 5px;
  border-radius: 4px;
  transition: all 0.3s;
}

.close-btn:hover {
  background: #f8f9fa;
  color: #2c3e50;
}

.modal-content {
  padding: 20px;
  overflow-y: auto;
  flex: 1;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 详情网格 */
.detail-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 15px;
}

.detail-item {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.detail-item.full-width {
  grid-column: 1 / -1;
}

.detail-item label {
  font-weight: 600;
  color: #2c3e50;
  font-size: 14px;
}

.description-content {
  background: #f8f9fa;
  padding: 12px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  white-space: pre-wrap;
  word-break: break-word;
}

.code-block {
  background: #f8f9fa;
  padding: 15px;
  border-radius: 6px;
  border: 1px solid #e9ecef;
  overflow-x: auto;
  font-family: monospace;
  font-size: 13px;
  max-height: 300px;
}

.error-stack {
  color: #e74c3c;
}

.error-info {
  display: flex;
  flex-direction: column;
  gap: 15px;
}

.error-title {
  background: #ffebee;
  color: #d32f2f;
  padding: 15px;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 10px;
  font-weight: 500;
}

.error-details h4,
.error-data h4 {
  margin: 0 0 10px 0;
  color: #2c3e50;
  font-size: 16px;
}

.warning-text {
  color: #e74c3c;
  font-weight: 500;
}

/* 提示框 */
.toast {
  position: fixed;
  top: 20px;
  right: 20px;
  background: #2ecc71;
  color: white;
  padding: 15px 20px;
  border-radius: 6px;
  box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
  display: flex;
  align-items: center;
  gap: 10px;
  z-index: 1001;
}

.toast i {
  font-size: 18px;
}

.toast .close-btn {
  margin-left: auto;
  color: white;
}

.toast .close-btn:hover {
  background: rgba(255, 255, 255, 0.2);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .page-header,
  .pagination-container,
  .batch-actions {
    flex-direction: column;
    align-items: stretch;
  }
  
  .header-actions,
  .batch-buttons {
    justify-content: center;
  }
  
  .filter-row {
    flex-direction: column;
  }
  
  .filter-item {
    min-width: 100%;
  }
  
  .date-range-inputs {
    flex-direction: column;
    align-items: stretch;
  }
  
  .pagination-controls {
    justify-content: center;
    flex-wrap: wrap;
  }
  
  .detail-grid {
    grid-template-columns: 1fr;
  }
  
  .logs-table th,
  .logs-table td {
    padding: 8px;
    font-size: 12px;
  }
  
  .user-info {
    flex-direction: column;
    align-items: flex-start;
  }
}
</style>